package http;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;

public class HttpClient {

    public static Object[] request(String url,String method,String header,String data) throws Exception {
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        // 设置请求类型
        con.setRequestMethod(method);

        System.out.println(header);
        // 设置请求头
        String[] headers=header.split("\r\n");
        if (headers.length>1){
            //跳过第一行 Host
            for (String line : headers) {
                int pos = line.indexOf(": ");
                if (pos > 0) {
                    String key = line.substring(0, pos);
                    String value = line.substring(pos + 2);
                    //if (!key.contains("Host: "))
                    con.setRequestProperty(key, value);
                }
            }
        }

        System.out.println(data);
        if (!data.isEmpty()) {
            // 发送POST请求必须设置如下两行
            con.setDoOutput(true);
            con.setDoInput(true);

            // 写入数据
            try (OutputStream os = con.getOutputStream()) {
                byte[] input = data.getBytes();
                os.write(input, 0, input.length);
            }
        }

        int responseCode = con.getResponseCode();
        System.out.println("Response Code : " + responseCode);

        // 读取响应
        String inputLine;
        StringBuilder response = new StringBuilder();

        if (responseCode==200) {
            BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
        }

        StringBuilder stringHeader= new StringBuilder();
        Map<String, List<String>> responseHeaders = con.getHeaderFields();
        for (Map.Entry<String, List<String>> entry : responseHeaders.entrySet()) {
            //System.out.println(entry.getKey() + " : " + entry.getValue());
            if (!(entry.getKey() ==null)) stringHeader.append(entry.getKey()).append(" : ").append(entry.getValue().get(0)).append("\r\n");
        }

        // 打印结果
        System.out.println(stringHeader);
        System.out.println(response);
        return new Object[] { responseCode, stringHeader.toString(), response.toString()};
    }
}
